<script setup lang="ts">
import { ref, computed } from "vue"
import { $t } from '#/locales'
import { ElMessage  } from "element-plus";
import { createSysMenuApi, updateSysMenuApi } from '#/api/system/menuMgr';
import {Ellipsis, IconifyIcon} from '@vben/icons';
import { SelectIconDialog } from './index'

defineOptions({ name: 'Dialog' })
const selectIconDialogRef = ref<InstanceType<typeof SelectIconDialog> | null>(null)

const menuNameTxt = $t('common.inputPhTxt', [$t('systemMenu.nameTxt')])
const pathTxt = $t('common.selectPhTxt', [$t('systemMenu.routePathTxt')])

defineProps({

});

const titleTxt = {
  sublevel: $t('common.newTxt'),
  plevel: $t('common.newTxt'),
  edit: $t('common.editTxt'),
}

const emit = defineEmits(['queryTable'])
const submitLoading = ref(false)
const dialogVisible = ref(false)
const formRef = ref()
const defaultFormInline = {
  name: "",
  visible: 'disable',
  icon: "",
  parentMenuId: "",
  path: "",
  sort: null,
  permissionIdentification: ""
}
const formInline = ref({ ...defaultFormInline })
const editData = ref<any>(null)
const handleType = ref<any>('PLEVEL')
const listData = ref<any>([])
const rules = {
  name: [
    { required: true, message: menuNameTxt, trigger: 'blur' },
  ],
  path: [
    { required: true, message: pathTxt, trigger: 'change' },
  ]
}

const handleClose = () => {
  formInline.value = { ...defaultFormInline }
  listData.value = []
  formRef.value.resetFields()
  dialogVisible.value = false
}
const inint = (type: any, data: any) => {
  console.log(data)
  editData.value = data ?? null
  handleType.value = type.toLowerCase()
  if (type === 'EDIT') {
    const { name, parentMenuId, path, icon, sort, visible, permissionIdentification } = data
    formInline.value = { name, parentMenuId, path, icon, sort, visible, permissionIdentification }
    listData.value = data && data.parentMenuId !== '0' ? [{id: data.parentMenuId, name: data.parentMenuName}] : []
  }
  if (type === 'SUBLEVEL') {
    const {id} = data
    formInline.value.parentMenuId = id
    listData.value = [data] 
  }
  dialogVisible.value = true
}
const showIconSelector = () => {
  console.log('showIconSelector')
  selectIconDialogRef.value?.inint()
}

const submit = () => {
  if (!formRef) return
  formRef.value?.validate((valid: any) => {
    if (valid) {
      let params = { ...formInline.value } as any

      if (handleType.value === 'edit') {
        params['id'] = editData.value.id
      }
      submitLoading.value = true
      const Api = handleType.value === 'edit' ? updateSysMenuApi(params) : createSysMenuApi(params)
      Api.then(() => {
        ElMessage.success($t('common.handleTxt', [$t('common.successTxt')]))
        emit('queryTable')
        handleClose()
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

const lucideIconName = computed(() => {
  if (!formInline.value.icon) return ''
  return `lucide:${formInline.value.icon.toLowerCase()}`
})

const updateIcon = (icon: string) => {
  formInline.value.icon = icon.toLowerCase()
}

defineExpose({ inint })
</script>
<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :title="titleTxt[handleType as keyof typeof titleTxt]"
    width="800" :append-to-body="true" :close-on-click-modal="false" :before-close="handleClose">
    <el-form class="flex flex-wrap" ref="formRef" :model="formInline" :rules="rules" label-width="80px">
      <el-form-item :label="$t('systemMenu.nameTxt')" prop="name">
        <el-input v-model="formInline.name" clearable :maxlength="50" :placeholder="menuNameTxt" />
      </el-form-item>
      <el-form-item :label="$t('systemMenu.parMenuTxt')">
        <el-cascader :disabled="handleType === 'edit' || handleType === 'sublevel'" clearable :show-all-levels="false" class="w-full" v-model="formInline.parentMenuId"
          :placeholder="$t('common.selectPhTxt', [$t('systemMenu.parMenuTxt')])" :options="listData"
          :props="{ emitPath: false, checkStrictly: true, multiple: false, label: 'name', value: 'id', children: 'children' }" />
      </el-form-item>
      <el-form-item prop="path" :label="$t('systemMenu.pathTxt')">
        <el-input v-model="formInline.path" clearable :maxlength="50" :placeholder="pathTxt" />
      </el-form-item>
      <el-form-item :label="$t('systemMenu.iconTxt')">
        <el-input class="icon-input" clearable :maxlength="0" v-model="formInline.icon">
          <template #prefix>
            <IconifyIcon v-if="!!formInline.icon" :icon="lucideIconName" class="el-input__icon" style="color: #191919" />
            <span v-else>{{$t('common.selectPhTxt', [$t('systemMenu.iconTxt')])}}</span>
          </template>
          <template #suffix>
            <el-icon class="cursor-pointer" @click="showIconSelector"><Ellipsis /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('common.sortTxt')">
        <el-input v-model="formInline.sort" clearable :maxlength="50"
          :placeholder="$t('common.inputPhTxt', [$t('common.sortTxt')])" />
      </el-form-item>
      <el-form-item :label="$t('common.statusTxt')">
        <el-radio-group v-model="formInline.visible">
          <el-radio value="enable">{{ $t('common.showTxt') }}</el-radio>
          <el-radio value="disable">{{ $t('common.fiddenTxt') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('systemMenu.permissionIdentificationTxt')">
        <el-input v-model="formInline.permissionIdentification" clearable :maxlength="50"
          :placeholder="$t('common.inputPhTxt', [$t('systemMenu.permissionIdentificationTxt')])" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="handleClose">
          {{ $t('common.cancelTxt') }}
        </el-button>
        <el-button type="primary" @click="submit" :loading="submitLoading">
          {{ $t('common.submitTxt') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
  <SelectIconDialog ref="selectIconDialogRef" @updateIcon="updateIcon" :icon="formInline.icon"></SelectIconDialog>
</template>
<style lang="scss" scoped>
.el-form-item {
  width: calc((100% - 10px) / 2);
  &:nth-of-type(2n+1) {
    margin-right: 10px;
  }
}
.icon-input {
  :deep(.el-input__inner) {
    font-size: 0px;
  }
}
</style>
